//
//  NSDate+RBExtension.m
//  Budejie
//
//  Created by 华杨科技 on 2017/11/27.
//  Copyright © 2017年 饶波. All rights reserved.
//

#import "NSDate+RBExtension.h"

static NSDateComponents *cmps_ ; // 定义成全局变量(习惯在后面添加下划线)，避免重复创建
@implementation NSDate (RBExtension)

- (BOOL)rb_isThisYear
{
    // 2017-11-25 10:15:48   ----   2017 
    cmps_ = [self rb_compareDate];
    return cmps_.year == 0;
}

- (BOOL)rb_isToday
{
    cmps_ = [self rb_compareDate];
    return cmps_.year==0 && cmps_.month==0 && cmps_.day==0; // 千万别写成 date了
}

- (BOOL)rb_isYesterday
{
    // 日期元素对象
    NSDateComponents *cmps = [self rb_compareDate];
    
    return  cmps.year == 0 && cmps.month==0 && cmps.day==1;
}

- (NSDateComponents *)rb_compareDate
{
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM:dd";
    
    // 只比较年月日
    // 2017-11-25 11:25:36   --- > 2017-11-25 00:00:00 
    
    NSString *selfString = [fmt stringFromDate:self];
    NSString *nowStr = [fmt stringFromDate:[NSDate date]];
    
    NSDate *selfDate = [fmt dateFromString:selfString];
    NSDate *nowDate = [fmt dateFromString:nowStr];
    
    NSCalendar *calendar = [self rb_calendar];
    NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;
    
    // The resulting component values may be negative if resultDate is before startDate. 
    // 如果结束日期在前:结果就是一个负数，反之就是正数
    // 这样表示更具体:前面的日期《 后面的日期，结果就是负数；反之。
    return [calendar components:unit fromDate:selfDate toDate:nowDate options:0];
}

#pragma mark - 一:日期比较:返回日期比较对象
- (NSDateComponents *)rb_intervalToDate:(NSDate *)date
{
    NSCalendar *calendar = [self rb_calendar];
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
   return [calendar components:unit fromDate:self toDate:date options:0];
}

- (NSDateComponents *)rb_intervalToNow
{
   return [self rb_intervalToDate:[NSDate date]];
}

/**返回日历对象*/
- (NSCalendar *)rb_calendar
{
    NSCalendar *calendar = nil;
    if ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0) {
        calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]; //iOS8 之后可用
    }else{
        calendar = [NSCalendar currentCalendar];   
    }
    return calendar;
}
@end
